/* 5. 修改书籍信息 */
const CHECK = require('../myUtil/formatCheck');
const db = require('../../coSqlite3');
const HTM = require('../myUtil/lib').html;

exports.updateBook = function* (req, res) {
    console.log("----------------------5. 修改书籍信息\n");
    let bID = req.body.bID;
    let bName = req.body.bName;
    let bPub = req.body.bPub;
    let bDate = req.body.bDate;
    let bAuthor = req.body.bAuthor;
    let bMem = req.body.bMem;

    let htm = HTM.divBegin + 2 + HTM.divEnd + '提交的参数有误：';
    if (bID == '') {
        return HTM.begin + htm + '书号不能为空' + HTM.end;
    } else if (bID.length > 30) {
        return HTM.begin + htm + '书号长度不能超过30' + HTM.end;
    }

    if (bName == '') {
        return HTM.begin + htm + '书名不能为空' + HTM.end;
    } else if (bName.length > 30) {
        return HTM.begin + htm + '书名长度不能超过30' + HTM.end;
    }

    if (bPub.length > 30) {
        return HTM.begin + htm + '出版社长度不能超过30' + HTM.end;
    }

    if (bDate != '') {
        if (!CHECK.dataFormatCheck(bDate)) {
            return HTM.begin + htm + '出版日期格式不正确' + HTM.end;
        }
    }

    if (bAuthor.length > 20) {
        return HTM.begin + htm + '作者长度不能超过20' + HTM.end;
    }

    if (bMem.length > 30) {
        return HTM.begin + htm + '内容摘要长度不能超过30' + HTM.end;
    }

    let array = [bName, bPub, bDate, bAuthor, bMem, bID];
    let args = [];
    let trueORFalse = [];
    for (let item of array) {
      if (item != "") {
          trueORFalse.push(true);
          args.push(item);
          continue;
        }
        trueORFalse.push(false);
    }
    htm = HTM.divBegin + 1 + HTM.divEnd;
    try {
        let exist = yield db.execSQL('SELECT count(bID) as count FROM book WHERE bID = ?', [bID]);
        if (exist[0].count <= 0) {
            return HTM.begin + htm + '该书不存在' + HTM.end;
        }

        // yield db.execSQL("PRAGMA foreign_keys = 1");
        yield db.execSQL('update book set ' + 
            (trueORFalse[0] ? " bname = ?" : "") + // bname是必填项，不为空
            (trueORFalse[1] ? ", bpub = ? " : "") +
            (trueORFalse[2] ? ", bdate = ? " : "") +
            (trueORFalse[3] ? ", bauthor = ? " : "") +
            (trueORFalse[4] ? ", bmem = ? " : "") +
            " where bid = ?",
            args);
        if (trueORFalse[0]) {
            yield db.execSQL ('update process set bname = ? where bid = ?', [bName, bID]);
        }
    
    } catch (err) {
        htm = HTM.divBegin + 3 + HTM.divEnd + "数据库执行失败: ";
        return HTM.begin + htm + err + HTM.end;
    }

    htm = HTM.divBegin + 0 + HTM.divEnd;

    return HTM.begin + htm + '成功' + HTM.end;
}